package leetcode;

import java.util.ArrayList;
import java.util.List;

class Solution_131 {
    List<List<String>> result = new ArrayList<>();
    List<String> path = new ArrayList<>();
    boolean[][] isPalindrome; //存放是否是回文字符串
    public List<List<String>> partition(String s) {
        if (s.isEmpty()) return result;
        isPalindrome = isPalindrome(s);
        backtracking(s,0);
        return result;
    }
    public void backtracking(String s, int start){
        if (start >= s.length()){
            result.add(new ArrayList<>(path));
        }
        for (int i = start; i < s.length(); i++) {
            if (isPalindrome[start][i]){
                path.add(s.substring(start,i + 1));
                backtracking(s,i + 1);
                path.removeLast();
            }
        }
    }
    public boolean[][] isPalindrome(String s){
        boolean[][] res = new boolean[s.length()][s.length()];
        for (int i = 0; i < s.length(); i++) {
            res[i][i]= true;
        }
        for (int start = s.length() -1; start >= 0; start--) {
            for (int end = start; end < s.length(); end++) {
                if (s.charAt(start) == s.charAt(end)){
                    if (end - start <= 1){
                        res[start][end] = true;
                    }else {
                        if (res[start + 1][end -1]) {
                            res[start][end] = true;
                        }else {
                            res[start][end] = false;
                        }
                    }
                }else {
                    res[start][end] = false;
                }
            }
        }
        return res;
    }
}